//
//  RootViewController.m
//  ProvinceCityAreaSelector
//
//  Created by apple on 14-3-17.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "SBJson.h"
#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _selectRow = 0;
        _stringCityParentID = @"2";
        _stringAreaParentID = @"52";
        _arrProvince = [[NSMutableArray alloc] initWithCapacity: 0];
        _arrCity = [[NSMutableArray alloc] initWithCapacity: 0];
        _arrArea = [[NSMutableArray alloc] initWithCapacity: 0];
        //    获取txt文件路径
        NSString *txtPath = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"txt"];
        //    将txt到string对象中，编码类型为NSUTF8StringEncoding
        NSString *areaString = [[NSString  alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];
        
        //    NSLog(@"areaString = %@", areaString);
        
        _arrJson = [areaString JSONValue];
        NSLog(@"dictJson = %@, [_arrJson count] = %d", _arrJson, [_arrJson count]);
//        for (NSDictionary *dict in _arrJson)
//        {
//            ModelProvince *model = [[ModelProvince alloc] init];
//            
//            model.parent_id = [dict objectForKey: @"parent_id"];
//            model.region_id = [dict objectForKey: @"region_id"];
//            model.region_name = [dict objectForKey: @"region_name"];
//            model.region_type = [dict objectForKey: @"region_type"];
//            
//            if ([model.region_type isEqualToString: @"1"])
//            {
//                [_arrProvince addObject: model];
//            }
//            else if ([model.region_type isEqualToString: @"2"])
//            {
//                [_arrCity addObject: model];
//            }
//            else if ([model.region_type isEqualToString: @"3"])
//            {
//                [_arrArea addObject: model];
//            }
//            
//        }
//        
//        NSLog(@"[_arrProvince count] =%d, [_arrCity count] = %d, [_arrArea count]= %d", [_arrProvince count], [_arrCity count], [_arrArea count]);

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *btnCreatPlist = [UIButton buttonWithType: UIButtonTypeRoundedRect];
//    [btnCreatPlist setBackgroundColor: [UIColor lightGrayColor]];
    [btnCreatPlist setFrame: CGRectMake(20, 20, 280, 40)];
    [btnCreatPlist addTarget: self action: @selector(onCreatPlistButtonClick) forControlEvents: UIControlEventTouchUpInside];
    [btnCreatPlist setTitle: @"生成Plist" forState: UIControlStateNormal];
    [self.view addSubview: btnCreatPlist];
    
    NSArray *arrDst = @[@"北京", @"北京", @"东城区"];
    for (int i = 0; i < 3; i ++)
    {
        UIButton *button = [UIButton buttonWithType: UIButtonTypeRoundedRect];
        [button setFrame: CGRectMake(20, 80 + 60 * i, 280, 40)];
//        [button setBackgroundColor: [UIColor lightGrayColor]];
        [button setTag: 100 + i];
        [button setTitle: [arrDst objectAtIndex: i] forState: UIControlStateNormal];
        [button addTarget: self action: @selector(onButtonClick:) forControlEvents: UIControlEventTouchUpInside];
        [self.view addSubview: button];
    }
}

- (void) initPickerView
{
    _actionSheet = [[UIActionSheet alloc] initWithTitle:@"  " delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"",@"",@"",@"",nil];
    [_actionSheet setBackgroundColor: [UIColor whiteColor]];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [_actionSheet addSubview:toolbar];
    
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(onCancelButtonClick)];
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(onFinishButtonClick)];
    
    NSArray *itemArray = [NSArray arrayWithObjects:cancelItem,spaceItem,doneItem, nil];
    [toolbar setItems:itemArray];
    
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 44, 320, 216)];
    _pickerView.backgroundColor = [UIColor whiteColor];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.showsSelectionIndicator = YES;
    [_actionSheet addSubview: _pickerView];
//    [_actionSheet showFromTabBar: self.tabBarController.tabBar];
    [_actionSheet showInView: self.view];
}

#pragma mark- onCancelButtonClick
- (void) onCancelButtonClick
{
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark-onFinishButtonClick
- (void) onFinishButtonClick
{
    [self selectDestinationWith: _selectRow];
    [_actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark-onButtonClick
- (void) onButtonClick: (UIButton *) theButton
{
    _selectRow = 0;
    if (theButton.tag == 100)
    {
        _selectDestStyle = SelectProvinceStyle;
        [_arrProvince removeAllObjects];

        for (NSDictionary *dict in _arrJson)
        {
            ModelProvince *model = [[ModelProvince alloc] init];
            
            model.parent_id = [dict objectForKey: @"parent_id"];
            model.region_id = [dict objectForKey: @"region_id"];
            model.region_name = [dict objectForKey: @"region_name"];
            model.region_type = [dict objectForKey: @"region_type"];
            
            if ([model.region_type isEqualToString: @"1"])
            {
                [_arrProvince addObject: model];
            }
            
        }
        
        _arrPickerViewData = _arrProvince;
        NSLog(@"[_arrPickerViewData count] = %d, [_arrProvince count] = %d", [_arrPickerViewData count], [_arrProvince count]);

//        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 216, 320, 216)];
//        [_pickerView setBackgroundColor: [UIColor lightGrayColor]];
//        _pickerView.delegate = self;
//        _pickerView.dataSource = self;
//        _pickerView.showsSelectionIndicator = YES;
//        [self.view addSubview: _pickerView];
    }
    else if (theButton.tag == 101)
    {
        _selectDestStyle = SelectCityStyle;
        
        [_arrCity removeAllObjects];
        
        for (NSDictionary *dict in _arrJson)
        {
            ModelProvince *model = [[ModelProvince alloc] init];
            
            model.parent_id = [dict objectForKey: @"parent_id"];
            model.region_id = [dict objectForKey: @"region_id"];
            model.region_name = [dict objectForKey: @"region_name"];
            model.region_type = [dict objectForKey: @"region_type"];
            
            if ([model.parent_id isEqualToString: _stringCityParentID])
            {
                [_arrCity addObject: model];
            }

        }
        
        _arrPickerViewData = _arrCity;
        NSLog(@"[_arrPickerViewData count] = %d, [_arrCity count] = %d", [_arrPickerViewData count], [_arrCity count]);
        
//        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 216, 320, 216)];
//        [_pickerView setBackgroundColor: [UIColor lightGrayColor]];
//        _pickerView.delegate = self;
//        _pickerView.dataSource = self;
//        _pickerView.showsSelectionIndicator = YES;
//        [self.view addSubview: _pickerView];
    }
    else
    {
        _selectDestStyle = SelectAreaStyle;
        
        [_arrArea removeAllObjects];
        NSLog(@"_stringAreaParentID = %@", _stringAreaParentID);
        for (NSDictionary *dict in _arrJson)
        {
            ModelProvince *model = [[ModelProvince alloc] init];
            
            model.parent_id = [dict objectForKey: @"parent_id"];
            model.region_id = [dict objectForKey: @"region_id"];
            model.region_name = [dict objectForKey: @"region_name"];
            model.region_type = [dict objectForKey: @"region_type"];
            
            if ([model.parent_id isEqualToString: _stringAreaParentID])
            {
                [_arrArea addObject: model];
            }
            
        }
        
        _arrPickerViewData = _arrArea;
        NSLog(@"[_arrPickerViewData count] = %d, [_arrArea count] = %d", [_arrPickerViewData count], [_arrArea count]);
        
//        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 216, 320, 216)];
//        [_pickerView setBackgroundColor: [UIColor lightGrayColor]];
//        _pickerView.delegate = self;
//        _pickerView.dataSource = self;
//        _pickerView.showsSelectionIndicator = YES;
//        [self.view addSubview: _pickerView];

    }
    
    [self initPickerView];
}

#pragma mark-onCreatPlistButtonClick
- (void) onCreatPlistButtonClick
{
    //    获取txt文件路径
    NSString *txtPath = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"txt"];
    //    将txt到string对象中，编码类型为NSUTF8StringEncoding
    NSString *areaString = [[NSString  alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];
    
//    NSLog(@"areaString = %@", areaString);

    NSDictionary *dictJson = [areaString JSONValue];
    NSLog(@"dictJson = %@", dictJson);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UIPickerView Delegate Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([_arrPickerViewData count] == 0)
    {
        return 1;
    }
    return [_arrPickerViewData count];
}

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([_arrPickerViewData count] == 0)
    {
        return @"";
    }
    ModelProvince *model = [_arrPickerViewData objectAtIndex: row];
    return model.region_name;
}

- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.minimumFontSize = 17;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.backgroundColor = [UIColor clearColor];
        [pickerLabel setFont:[UIFont systemFontOfSize: 17]];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"********* row = %d *********", row);
    _selectRow = row;
    [self selectDestinationWith: row];
}

#pragma mark-
#pragma mark- select Dest
- (void) selectDestinationWith:(NSInteger) row
{
    if ([_arrPickerViewData count] == 0)
    {
        return;
    }
    
    ModelProvince *model=[_arrPickerViewData objectAtIndex: row];
    
    UIButton *buttonCity = nil;
    UIButton *buttonArea = nil;
    if (_selectDestStyle == SelectProvinceStyle)
    {
        _stringCityParentID = model.region_id;
        ModelProvince *modelCity = nil;
        NSString *stringCityParentID = nil;
        
        UIButton *buttonProvince = (UIButton *)[self.view viewWithTag: 100];
        [buttonProvince setTitle: model.region_name forState: UIControlStateNormal];
        
        buttonCity = (UIButton *) [self.view viewWithTag: 101];
        for (NSDictionary *dict in _arrJson)
        {
            modelCity = [[ModelProvince alloc] init];
            
            _stringCityParentID = modelCity.parent_id = [dict objectForKey: @"parent_id"];
            stringCityParentID = modelCity.region_id = [dict objectForKey: @"region_id"];
            modelCity.region_name = [dict objectForKey: @"region_name"];
            modelCity.region_type = [dict objectForKey: @"region_type"];
            
            if ([modelCity.parent_id isEqualToString: model.region_id])
            {
                [buttonCity setTitle: modelCity.region_name forState: UIControlStateNormal];
                break;
            }
            
        }
        
        UIButton *buttonArea = (UIButton *) [self.view viewWithTag: 102];
        for (NSDictionary *dict in _arrJson)
        {
            ModelProvince *modelArea = [[ModelProvince alloc] init];
            
            modelArea.parent_id = [dict objectForKey: @"parent_id"];
            modelArea.region_id = [dict objectForKey: @"region_id"];
            modelArea.region_name = [dict objectForKey: @"region_name"];
            modelArea.region_type = [dict objectForKey: @"region_type"];
            _stringAreaParentID = modelArea.parent_id;
            if ([modelArea.parent_id isEqualToString: stringCityParentID])
            {
                [buttonArea setTitle: modelArea.region_name forState: UIControlStateNormal];
                break;
            }
            
        }
    }
    else if (_selectDestStyle  ==  SelectCityStyle)
    {
        _stringAreaParentID = model.region_id;
        buttonCity = (UIButton *)[self.view viewWithTag: 101];
        [buttonCity setTitle: model.region_name forState: UIControlStateNormal];
        NSLog(@"model.region_id = %@", model.region_id);
        buttonArea = (UIButton *) [self.view viewWithTag: 102];
        
        NSMutableArray *arrArea = [[NSMutableArray alloc] initWithCapacity: 0];
        for (NSDictionary *dict in _arrJson)
        {
            ModelProvince *modelArea =[[ModelProvince alloc] init];
            
            modelArea.parent_id = [dict objectForKey: @"parent_id"];
            modelArea.region_id = [dict objectForKey: @"region_id"];
            modelArea.region_name = [dict objectForKey: @"region_name"];
            modelArea.region_type = [dict objectForKey: @"region_type"];
            
            if ([modelArea.parent_id isEqualToString: model.region_id])
            {
                [arrArea addObject: modelArea];
                [buttonArea setTitle: modelArea.region_name forState: UIControlStateNormal];
                break;
            }
        }
        
        if ([arrArea count] == 0)
        {
            [buttonArea setTitle: @"" forState: UIControlStateNormal];
        }
    }
    else if (_selectDestStyle == SelectAreaStyle)
    {
        buttonArea = (UIButton *)[self.view viewWithTag: 102];
        [buttonArea setTitle: model.region_name forState: UIControlStateNormal];
    }
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         _pickerView.frame = CGRectMake(0, _pickerView.frame.origin.y+_pickerView.frame.size.height, _pickerView.frame.size.width, _pickerView.frame.size.height);
                     }
                     completion:^(BOOL finished){
                         [_pickerView removeFromSuperview];
                         
                     }];
}

@end
